<template>
    <div class="madp-customer-data">
        <basic-container>
            <el-form :inline="true" :model="searchParams" class="madp-searchbox">
                <el-form-item v-if="!batchEdit && permissions.cp_customer_data_edit">
                    <el-button type="primary" @click="doEdit">批量修改</el-button>
                </el-form-item>
                <el-form-item v-else-if="permissions.cp_customer_data_edit">
                    <el-button @click="cancelEdit">取消</el-button>
                    <el-button type="primary" @click="editAll()">提交</el-button>
                </el-form-item>
                <div>
                    <el-form-item>
                        <el-select v-model="searchParams.status" placeholder="请选择状态">
                            <el-option v-for="(item, index) in statusList" :key="index" :label="item.label" :value="item.value"></el-option>
                        </el-select>
                    </el-form-item>
                    <el-form-item>
                        <el-button type="primary" @click="handleSearch">搜索</el-button>
                        <el-button @click="clearSearch">清空</el-button>
                    </el-form-item>
                </div>
            </el-form>
            <!-- 表格 -->
            <el-table
                :header-cell-style="{
                    background: 'rgb(255, 191, 191)',
                    color: 'rgb(44,44,44)'
                }"
                stripe
                v-loading="loading"
                :data="tableData"
            >
                <el-table-column prop="label" label="字段名称" align="center"></el-table-column>
                <el-table-column label="排序展示" align="center">
                    <template slot-scope="scope">
                        <el-form :model="scope.row" :rules="rules" ref="scope.row">
                            <el-form-item prop="order" class="madp-form-item">
                                <div v-if="!batchEdit || scope.row.isSys === 1">{{ scope.row.order }}</div>
                                <el-input v-else v-model.trim="scope.row.order" type="number" min="0" max="100" @blur="checkRowOrder(scope.row)"></el-input>
                            </el-form-item>
                        </el-form>
                    </template>
                </el-table-column>
                <el-table-column label="状态" align="center">
                    <template slot-scope="scope">
                        <div v-if="!batchEdit">{{ scope.row.status === 0 ? '关闭' : '开启' }}</div>
                        <div v-else>
                            <el-radio-group v-model="scope.row.status">
                                <el-radio :label="1">开启</el-radio>
                                <el-radio :label="0">关闭</el-radio>
                            </el-radio-group>
                        </div>
                    </template>
                </el-table-column>
                <el-table-column label="操作" align="center" v-if="!batchEdit && (permissions.cp_customer_data_open || permissions.cp_customer_data_close || permissions.cp_customer_data_edit)">
                    <template slot-scope="scope">
                        <div v-if="!batchEdit">
                            <el-button v-if="permissions.cp_customer_data_open && scope.row.status === 0" @click="handleStatus(scope.row)" type="text">开启</el-button>
                            <el-button v-if="permissions.cp_customer_data_close && scope.row.status != 0" @click="handleStatus(scope.row)" type="text">关闭</el-button>
                            <el-button v-if="permissions.cp_customer_data_edit" type="text" @click="showDialog('editForm', scope.row)">编辑</el-button>
                        </div>
                    </template>
                </el-table-column>
            </el-table>
            <!-- 分页 -->
            <el-pagination
                background
                class="madp-pagination"
                @size-change="handleSizeChange"
                @current-change="handleCurrentChange"
                :current-page="page.current"
                :page-sizes="[10, 20, 30, 50, 100]"
                :page-size="page.size"
                layout="total, sizes, prev, pager, next, jumper"
                :total="page.total"
            ></el-pagination>
            <!-- 新增/编辑 弹框 -->
            <el-dialog :title="dialogTitle" :visible.sync="dialogShow" width="55%" v-if="dialogShow" @close="closeDialog(formName)" :close-on-click-modal="false">
                <div class="madp-imgbox-top">
                    <el-form :model="dialogForm" :rules="rules" :ref="formName" label-width="100px">
                        <el-form-item label="字段名称" prop="label">
                            <el-input class="dialog-input" maxlength="20" v-model.trim="dialogForm.label" disabled placeholder="请输入字段名称"></el-input>
                        </el-form-item>
                        <el-form-item label="排序展示" prop="order">
                            <el-input
                                class="dialog-input"
                                v-model.number="dialogForm.order"
                                type="number"
                                @input="numberChange(arguments[0], 100)"
                                @change="numberChange(arguments[0], 100)"
                                placeholder="请输入0到100之间的数字"
                            ></el-input>
                        </el-form-item>
                        <el-form-item label="使用状态" prop="status">
                            <el-radio-group v-model="dialogForm.status">
                                <el-radio :label="1">开启</el-radio>
                                <el-radio :label="0">关闭</el-radio>
                            </el-radio-group>
                        </el-form-item>
                    </el-form>
                </div>
                <span slot="footer">
                    <el-button @click="closeDialog(formName)">取消</el-button>
                    <el-button @click="submitForm(formName)" type="primary">确定</el-button>
                </span>
            </el-dialog>
        </basic-container>
    </div>
</template>

<script>
import { addCustomerInfo, getCustomerList, changeCusStatus, updateCustomerInfo, updateCustomerAll, deleteCustomer, contactfieldTypeList } from '@/api/customer/customer-info';
import { mapGetters } from 'vuex';
export default {
    name: 'madp-customer-data',
    data() {
        let checkOrder = function(rule, value, callback) {
            if (value) {
                //正则
                let patt = /^(?:[1-9]?\d|100)$/;
                //检测排序输入
                if (patt.test(value) && value <= 100) {
                    callback();
                } else {
                    callback(new Error('排序值只能是0到100之间的整数！'));
                }
            } else {
                callback();
            }
        };
        return {
            // 状态list
            statusList: [{ label: '开启', value: 1 }, { label: '关闭', value: 0 }],
            // 字段类型列表
            typeList: [],
            //  新建/编辑 客户资料
            addForm: {
                order: 0,
                type: '',
                label: '',
                options: '',
                status: 1
            },
            // 编辑表单
            editForm: {},
            // 表单校验规则
            rules: {
                label: [
                    {
                        required: true,
                        message: '请输入字段名称',
                        trigger: 'blur'
                    },
                    {
                        min: 2,
                        max: 8,
                        message: '长度在 2 到 8 个字符',
                        trigger: 'blur'
                    },
                    {
                        message: '仅支持输入中文、英文或者中英文组合!',
                        trigger: 'blur',
                        pattern: /^[\u4e00-\u9fa5a-zA-Z]*$/
                    }
                ],
                type: [
                    {
                        required: true,
                        message: '请选择字段类型',
                        trigger: 'change'
                    }
                ],
                options: [
                    {
                        required: true,
                        message: '请填写选项内容',
                        trigger: 'blur'
                    }
                ],
                order: [
                    {
                        required: true,
                        validator: checkOrder,
                        trigger: 'blur'
                    }
                ]
            },
            // 弹窗标题
            dialogTitle: '',
            // 弹窗表单
            dialogForm: {},
            formName: 'addForm',
            // 弹窗开关
            dialogShow: false,
            // 表格相关数据
            loading: false,
            // 表格数据
            tableData: [],
            // 查询参数
            searchParams: {},
            // 分页
            page: {
                current: 1,
                size: 10,
                total: 100
            },
            // 批量修改编辑状态控制
            batchEdit: false
        };
    },
    computed: {
        ...mapGetters(['permissions'])
    },
    created() {
        let lett = this;
        document.onkeydown = function(e) {
            let key = window.event.keyCode;
            if (key == 13) {
                lett.validInput();
            }
        };
    },
    mounted() {
        this.getTableList();
        this.getTypeList();
    },
    methods: {
        // 数字修改
        numberChange(val, maxNum) {
            this.dialogForm.order = Number(this.dialogForm.order);
            this.$nextTick(() => {
                let num = Math.min(Number(this.dialogForm.order), maxNum);
                if (num < 0) {
                    this.dialogForm.order = 0;
                } else {
                    this.dialogForm.order = num;
                }
            });
        },
        // 获取字段类型列表
        getTypeList() {
            contactfieldTypeList().then((res) => {
                if (res.data && res.data.code === 0) {
                    this.typeList = res.data.data;
                }
            });
        },
        //初始化页面表格
        getTableList() {
            this.loading = true;
            let { current, size } = this.page;
            let obj = Object.assign(this.searchParams, { current, size });
            getCustomerList(obj).then((res) => {
                if (res.data && res.data.code === 0) {
                    const { records, total } = res.data.data;
                    if (this.batchEdit) {
                        this.tableData = records.map((item) => ({
                            ...item,
                            checkOrder: true
                        }));
                    } else {
                        this.tableData = records;
                    }
                    this.page.total = total;
                    this.loading = false;
                }
            });
        },
        // 当前页显示条数
        handleSizeChange(size) {
            this.page.size = size;
            this.page.current = 1;
            this.getTableList();
        },
        // 当前页码
        handleCurrentChange(current) {
            this.page.current = current;
            this.getTableList();
        },
        // 搜索
        handleSearch() {
            this.page.current = 1;
            this.getTableList();
        },
        clearSearch() {
            this.searchParams = {
                status: ''
            };
            this.page.current = 1;
            this.getTableList();
        },
        // 开启批量修改
        doEdit() {
            this.batchEdit = true;
            this.tableData.map((item) => {
                item.checkOrder = true;
            });
        },
        //取消批量修改
        cancelEdit() {
            this.batchEdit = false;
            this.getTableList();
        },
        //提交批量修改后的数据
        editAll() {
            let notValid = false;
            this.tableData.map((item) => {
                if (!item.checkOrder) {
                    notValid = true;
                }
            });
            if (notValid) {
                this.$message.error('请检查排序值');
                return;
            }
            let obj = {
                update: this.tableData
            };
            updateCustomerAll(obj).then((res) => {
                if (res.data && res.data.code === 0 && res.data.data) {
                    this.getTableList();
                    this.batchEdit = false;
                }
            });
        },
        // 判断每行排序取值
        checkRowOrder(row) {
            row.checkOrder = false;
            if (row.order) {
                //正则
                let reg = /^(?:[1-9]?\d|100)$/;
                //检测排序输入
                if (reg.test(row.order) && row.order <= 100) {
                    row.checkOrder = true;
                } else {
                    this.$message.error('排序值只能是0到100之间的整数！');
                }
            } else if (row.order === 0) {
                row.checkOrder = true;
            } else {
                this.$message.error('请输入排序值！');
            }
        },
        // 新建/编辑框
        showDialog(formName, row) {
            this.dialogShow = true;
            this.formName = formName;
            if (formName === 'addForm') {
                this.dialogTitle = '新增属性';
                this.dialogForm = this.addForm;
            } else {
                this.dialogTitle = '编辑属性';
                this.editForm = JSON.parse(JSON.stringify(row));
                this.dialogForm = this.editForm;
            }
        },
        //关闭新建/编辑弹窗
        closeDialog(formName) {
            this.dialogShow = false;
            if (formName === 'addForm') {
                this[formName] = {
                    order: 0,
                    type: '01',
                    label: '',
                    options: '',
                    status: 1
                };
            } else {
                this[formName] = {};
            }
        },
        validInput() {
            if (this.dialogForm.options && this.dialogForm.options.length > 12) {
                this.$message.error('选项文本内容不可超过12个字');
            }
        },
        //新增/编辑客户资料
        submitForm(formName) {
            this.$refs[formName].validate((valid) => {
                if (valid) {
                    let isRepeat = false;
                    let isNull = false;
                    let isOverLength = false;
                    if (this.dialogForm.options) {
                        let optionList = this.dialogForm.options.split('，');
                        // 判断重复
                        if (optionList.length > 1) {
                            let length = Array.from(new Set(optionList)).length;
                            if (optionList.length > length) {
                                isRepeat = true;
                            }
                        }
                        //遍历判断是否为空，空格或者长度超过12字
                        optionList.map((item, index) => {
                            if (item == '' || item == ' ') {
                                isNull = true;
                            }
                            if (item.length > 12) {
                                isOverLength = true;
                                this.$message.error('每个选项内容不能超过12个字');
                            }
                        });
                    }
                    if (isRepeat) {
                        this.$message.error('选项内容不能重复');
                        return;
                    }
                    if (isNull) {
                        this.$message.error('请输入正确的选项内容');
                        return;
                    }
                    if (isOverLength) {
                        return;
                    }
                    if (this.dialogForm.type !== '02' && this.dialogForm.type !== '03' && this.dialogForm.type !== '04') {
                        this.dialogForm.options = '';
                    }
                    if (formName === 'addForm') {
                        addCustomerInfo(this.dialogForm).then((res) => {
                            if (res.data && res.data.code === 0 && res.data.data) {
                                this.$message({
                                    type: 'success',
                                    message: '属性新增成功'
                                });
                                this.closeDialog(formName);
                                this.getTableList();
                            }
                        });
                    } else {
                        updateCustomerInfo(this.dialogForm).then((res) => {
                            if (res.data && res.data.code === 0 && res.data.data) {
                                this.$message({
                                    type: 'success',
                                    message: '属性编辑成功'
                                });
                                this.getTableList();
                                this.closeDialog(formName);
                            }
                        });
                    }
                }
            });
        },
        // 删除客户资料
        deleteRow(row) {
            this.$confirm('确认是否删除?', '提示', {
                confirmButtonText: '确定',
                cancelButtonText: '取消',
                type: 'warning'
            })
                .then(() => {
                    if (row.status === 0) {
                        deleteCustomer(row.id).then((res) => {
                            if (res.data && res.data.code === 0 && res.data.data) {
                                this.$message({
                                    type: 'success',
                                    message: '删除成功!'
                                });
                                this.getTableList();
                            } else {
                                this.$message({
                                    type: 'error',
                                    message: res.data.msg
                                });
                            }
                        });
                    } else {
                        this.$message({
                            type: 'error',
                            message: '该客户资料已被启用,删除失败!'
                        });
                    }
                })
                .catch(() => {});
        },
        //切换客户资料状态
        handleStatus(row) {
            let params = {
                id: row.id,
                status: row.status === 0 ? 1 : 0
            };
            changeCusStatus(params).then((res) => {
                if (res.data && res.data.code === 0 && res.data.data) {
                    this.getTableList();
                }
            });
        }
    }
};
</script>

<style lang="scss" scoped>
.madp-customer-data {
    .madp-explain {
        background-color: #fffbe6;
        border: 1px solid #ffe58f;
        color: rgba(0, 0, 0, 0.65);
        font-size: 14px;
        padding: 0 15px;
        line-height: 30px;
    }
    .madp-searchbox {
        display: flex;
        justify-content: space-between;
    }
    .madp-pagination {
        float: right;
        margin-top: 20px;
        margin-bottom: 20px;
    }
    .madp-imgbox-top {
        padding: 10px;
        span,
        p {
            line-height: 40px;
        }
        span {
            color: red;
        }
    }
}
.madp-form-item {
    margin-bottom: 0 !important;
}
.dialog-input {
    width: 60%;
}
</style>
